package com.xii.msmservice.controller;

import com.xii.commonutils.R;
import com.xii.commonutils.RandomUtil;
import com.xii.msmservice.service.MsmService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: 短信测试
 *
 * @return {@link null}
 * @author  wangxihao
 * @email wangxh0108@163.com
**/
@RequestMapping("/edumsm/msm")
@RestController
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;  //springboot自带的redis集成工具类
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //判断redis中是否有验证码  有的话就是还没有过期
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();
        //否则生成新的验证码
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(phone,param);
        if(isSend) {
            //存入redis并设置5分钟过期时间
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
